let ue = UE.getEditor("remark");
$(function () {
    query();
    $(".js-questions-item").unbind("click").click(function () {
        $("#questionsModal").modal("show");
    })
    $.ajax({
        url: "/ret/examget/getexamSortTree",
        type: "post",
        dataType: "json",
        success: function (data) {
            $.fn.zTree.init($("#menuTree"), setting1, data);
        }
    });
    $("#sortId").unbind("click").click(function (e) {
        e.stopPropagation();
        $("#menuContent").css({
            "width": $(this).outerWidth() + "px"
        }).slideDown(200);
    });
    $("body").unbind("click").click(function () {
        $("#menuContent").hide();
    });

    $("#menuContent").unbind("click").click(function (e) {
        e.stopPropagation();
    });
    $("#questionId").unbind("change").change(function () {
        let recordId = $(this).val();
        if (recordId != "") {
            $.ajax({
                url: "/ret/examget/getExamQuestionsById",
                type: "post",
                dataType: "json",
                data: {
                    recordId: recordId
                },
                success: function (data) {
                    if (data.status == "200") {
                        $("#questionTitle").html("试题标题：" + data.list.title + "<span style='float: right;margin-right: 10px;color: red;'>" + data.list.grade + "分</span>");
                        if (data.list.examType != "2") {
                            $("#content").show();
                            let childItemArr = JSON.parse(data.list.content);
                            createChildItem(childItemArr);
                        } else {
                            $("#content").hide();
                        }
                    } else if (data.status) {
                        layer.msg(sysmsg[data.msg]);
                    } else {
                        console.log(data.msg);
                    }
                }
            });
        } else {
            $("#questionTitle").html("");
            $("#child-item-table").html("");
        }
        $(".add-question").unbind("click").click(function () {
            let recordId = $("#questionId").val();
            $.ajax({
                url: "/ret/examget/getExamQuestionsById",
                type: "post",
                dataType: "json",
                data: {
                    recordId: recordId
                },
                success: function (data) {
                    if (data.status == "200") {
                        let index = $("#questionlist").find("tr").length;
                        let examType = "";
                        if (data.list.examType == "0") {
                            examType = "单选";
                        } else if (data.list.examType == "1") {
                            examType = "多选";
                        } else if (data.list.examType == "2") {
                            examType = "简述";
                        }
                        if (data.list.examType == "2") {
                            $("#questionlist").append("<tr data-value='" + recordId + "'><td>" + index + "</td><td>" + examType + "</td><td colspan='2'>" + data.list.title + "</td>" +
                                "<td><a onclick=\"deleteChildItem(this)\" class='btn btn-darkorange btn-xs'>删除</a>&nbsp;&nbsp;<a onclick=\"toup(this)\" class='btn btn-darkorange btn-xs'>上移</a>&nbsp;&nbsp;<a onclick=\"todown(this)\" class='btn btn-darkorange btn-xs'>下移</a></td></tr>");
                        } else {
                            let html = "";
                            let childItemArr = JSON.parse(data.list.content);
                            for (let i = 0; i < childItemArr.length; i++) {
                                html += childItemArr[i].optValue + "." + childItemArr[i].childTitle + "</br>";
                            }
                            $("#questionlist").append("<tr data-value='" + recordId + "'><td>" + index + "</td><td>" + examType + "</td><td>" + data.list.title + "</td>" +
                                "<td>" + html + "</td><td><a onclick=\"deleteChildItem(this)\" class='btn btn-darkorange btn-xs'>删除</a>&nbsp;&nbsp;<a onclick=\"toup(this)\" class='btn btn-darkorange btn-xs'>上移</a>&nbsp;&nbsp;<a onclick=\"todown(this)\" class='btn btn-darkorange btn-xs'>下移</a></td></tr>");
                        }
                    } else if (data.status == "100") {
                        layer.msg(sysmsg[data.msg]);
                    } else {
                        console.log(data.msg);
                    }
                    $("#questionsModal").modal("hide");
                }
            });

        })
    })
})

function query() {
    $("#myTable").bootstrapTable({
        url: '/ret/examget/getExamQuestionsRecordList',
        method: 'post',
        contentType: 'application/x-www-form-urlencoded',
        toolbar: '#toobar',//工具列
        striped: true,//隔行换色
        cache: false,//禁用缓存
        pagination: true,//启动分页
        sidePagination: 'server',//分页方式
        pageNumber: 1,//初始化table时显示的页码
        pageSize: 10,//每页条目
        showFooter: false,//是否显示列脚
        showPaginationSwitch: true,//是否显示 数据条数选择框
        sortable: true,//排序
        search: true,//启用搜索
        showColumns: true,//是否显示 内容列下拉框
        showRefresh: true,//显示刷新按钮
        idField: 'recordId',//key值栏位
        clickToSelect: true,//点击选中checkbox
        pageList: [10, 20, 30, 50],//可选择单页记录数
        queryParams: queryParams,
        columns: [{
            checkbox: true
        },
            {
                field: 'num',
                title: '序号',//标题  可不加
                width: '50px',
                formatter: function (value, row, index) {
                    return index + 1;
                }
            },
            {
                field: 'title',
                title: '考题标题',
                width: '200px',
                formatter: function (value, row, index) {
                    return "<a href=\"javascript:void(0);details('" + row.recordId + "')\" style='cursor: pointer'>" + value + "</a>";
                }
            },
            {
                field: 'remark',
                width: '200px',
                title: '备注'
            },
            {
                field: 'status',
                width: '50',
                title: '状态',
                formatter: function (value, row, index) {
                    if (value == "0") {
                        return "启用"
                    } else if (value == "1") {
                        return "停用";
                    } else {
                        return "未知";
                    }
                }
            },
            {
                field: 'createTime',
                width: '100px',
                title: '创建时间'
            },
            {
                field: 'opt',
                width: '150px',
                align: 'center',
                title: '操作',
                formatter: function (value, row, index) {
                    return createOptBtn(row.recordId, row.status);
                }
            }],
        onClickCell: function (field, value, row, $element) {
            //alert(row.SystemDesc);
        },
        responseHandler: function (res) {
            if (res.status == "500") {
                console.log(res.msg);
            } else if (res.status == "100") {
                layer.msg(sysmsg[res.msg]);
            } else {
                return {
                    total: res.list.total, //总页数,前面的key必须为"total"
                    rows: res.list.list //行数据，前面的key要与之前设置的dataField的值一致.
                };
            }
        }
    });
}

function queryParams(params) {
    let temp = {
        search: params.search,
        pageSize: this.pageSize,
        pageNumber: this.pageNumber,
        sort: params.sort,
        sortOrder: params.order,
        noticeType: $("#noticeType").val(),
        beginTime: $("#beginTime").val(),
        endTime: $("#endTime").val()
    };
    return temp;
};

function createOptBtn(recordId, status) {
    let html = "<a href=\"javascript:void(0);edit('" + recordId + "')\" class=\"btn btn-success btn-xs\" >编辑</a>&nbsp;&nbsp;";
    html += "<a href=\"javascript:void(0);del('" + recordId + "')\" class=\"btn btn-darkorange btn-xs\" >删除</a>&nbsp;&nbsp;";
    if (status == "1") {
        html += "<a href=\"javascript:void(0);setRecordStatus('" + recordId + "','0')\" class=\"btn btn-success btn-xs\" >启用</a>";
    } else {
        html += "<a href=\"javascript:void(0);setRecordStatus('" + recordId + "','1')\" class=\"btn btn-purple btn-xs\" >停用</a>";
    }
    return html;
}

function setRecordStatus(recordId, status) {
    $.ajax({
        url: "/set/examset/updateExamQuestionRecord",
        type: "post",
        dataType: "json",
        data: {
            recordId: recordId,
            status: status
        },
        success: function (data) {
            if (data.status == "500") {
                console.log(data.msg);
            } else if (data.status == "100") {
                layer.msg(sysmsg[data.msg]);
            } else {
                layer.msg(sysmsg[data.msg]);
                $("#myTable").bootstrapTable("refresh");
            }
        }
    })
}


function edit(recordId) {
    $("#listdiv").hide();
    $("#infodiv").show();
    document.getElementById("form1").reset();
    $(".js-back-btn").unbind("click").click(function () {
        goback();
    })
    ue.setContent("");
    $.ajax({
        url: "/ret/examget/getExamQuestionRecordById",
        type: "post",
        dataType: "json",
        data: {
            recordId: recordId
        },
        success: function (data) {
            if (data.status == "500") {
                console.log(data.msg);
            } else if (data.status == "100") {
                layer.msg(sysmsg[data.msg]);
            } else {
                let info = data.list;
                for (let id in info) {
                    if (id == "questionIds") {
                        getExamQuestionListByIds(info[id])
                    } else if (id == "remark") {
                        ue.setContent(info[id]);
                    } else {
                        $("#" + id).val(info[id]);
                    }
                }
            }
        }
    })

    $(".js-update-save").unbind("click").click(function () {
        updateExamQuestionRecord(recordId);
    })
}

function goback() {
    $("#infodiv").hide();
    $("#listdiv").show();
}

function del(recordId) {
    if (confirm("确定删除试卷记录吗？")) {
        $.ajax({
            url: "/set/examset/deleteExamQuestionRecord",
            type: "post",
            dataType: "json",
            data: {
                recordId: recordId
            },
            success: function (data) {
                if (data.status == "500") {
                    console.log(data.msg);
                } else if (data.status == "100") {
                    layer.msg(sysmsg[data.msg]);
                } else {
                    layer.msg(sysmsg[data.msg]);
                    $("#myTable").bootstrapTable("refresh");
                }
            }
        })
    }
}

function details(recordId) {
    window.open("/app/core/exam/examquestionrecorddetails?recordId=" + recordId);
}

function updateExamQuestionRecord(recordId) {
    $.ajax({
        url: "/set/examset/updateExamQuestionRecord",
        type: "post",
        dataType: "json",
        data: {
            recordId: recordId,
            sortNo: $("#sortNo").val(),
            title: $("#title").val(),
            questionIds: getParam(),
            remark: ue.getContent()
        },
        success: function (data) {
            if (data.status == "500") {
                console.log(data.msg);
            } else if (data.status == "100") {
                layer.msg(sysmsg[data.msg]);
            } else {
                layer.msg(sysmsg[data.msg]);
                $("#myTable").bootstrapTable("refresh");
            }
        }
    })
}

function getParam() {
    let paramArr = [];
    $("#questionlist").find("tr").next().each(function () {
        let recordId = $(this).attr("data-value");
        paramArr.push(recordId);
    });
    return paramArr.join(",");
}

let setting1 = {
    async: {
        enable: true,// 设置 zTree 是否开启异步加载模式
        url: "/ret/examget/getexamSortTree",// Ajax 获取数据的 URL 地址
        autoParam: ["sortId"],// 异步加载时需要自动提交父节点属性的参数
    },
    view: {
        dblClickExpand: false,
        selectedMulti: false
        //禁止多选
    },
    data: {
        simpleData: {
            enable: true,
            idKey: "sortId",
            pIdKey: "levelId",
            rootPId: "0"
        },
        key: {
            name: "sortName"
        }
    },
    callback: {
        onClick: function (e, treeId, treeNode) {
            let zTree = $.fn.zTree.getZTreeObj("menuTree"), nodes = zTree.getSelectedNodes(), v = "";
            let idem = $("#sortId");
            idem.attr("data-value", treeNode.sortId);
            idem.val(treeNode.sortName);
            getQuestionsList(treeNode.sortId)
        }
    }
};

function getQuestionsList(sortId) {
    $.ajax({
        url: "/ret/examget/getExamQuestListForSelectBySortId",
        type: "post",
        dataType: "json",
        data: {
            sortId: sortId
        },
        success: function (data) {
            if (data.status == "200") {
                let html = "<option value=''>请选择</option>";
                let infoList = data.list;
                for (let i = 0; i < infoList.length; i++) {
                    let examType = "";
                    if (infoList[i].examType == "1") {
                        examType = "单选";
                    } else if (infoList[i].examType == "2") {
                        examType = "多选";
                    } else {
                        examType = "简述";
                    }
                    html += "<option value='" + infoList[i].recordId + "'>【" + examType + "】" + infoList[i].title + "--分值：" + infoList[i].grade + "</option>";
                }
                $("#questionId").html(html);
            } else if (data.status == "200") {
                layer.msg(sysmsg[data.msg]);
            } else {
                console.log(data.msg);
            }

        }
    });
}

function createChildItem(childItemArr) {
    let html = "";
    for (let i = 0; i < childItemArr.length; i++) {
        html += "<tr><td>" + childItemArr[i].optValue + "</td>" +
            "<td>" + childItemArr[i].childTitle + "</td></tr>";
    }
    $("#child-item-table").html(html);
}

function deleteChildItem(Obj) {
    $(Obj).parent("td").parent("tr").remove();
}

function getExamQuestionListByIds(recordIds) {
    $.ajax({
        url: "/ret/examget/getExamQuestionListByIds",
        type: "post",
        dataType: "json",
        data: {
            recordIds: recordIds
        },
        success: function (data) {
            if (data.status == "500") {
                console.log(data.msg);
            } else if (data.status == "100") {
                layer.msg(sysmsg[data.msg]);
            } else {
                let listInfo = data.list;
                for (let i = 0; i < listInfo.length; i++) {
                    let info = listInfo[i];
                    let index = $("#questionlist").find("tr").length;
                    let examType = "";
                    if (info.examType == "0") {
                        examType = "单选";
                    } else if (info.examType == "1") {
                        examType = "多选";
                    } else if (info.examType == "2") {
                        examType = "简述";
                    }
                    if (info.examType == "2") {
                        $("#questionlist").append("<tr data-value='" + info.recordId + "'><td>" + index + "</td><td>" + examType + "</td><td colspan='2'>" + info.title + "</td>" +
                            "<td><a onclick=\"deleteChildItem(this)\" class='btn btn-darkorange btn-xs'>删除</a>&nbsp;&nbsp;<a onclick=\"toup(this)\" class='btn btn-darkorange btn-xs'>上移</a>&nbsp;&nbsp;<a onclick=\"todown(this)\" class='btn btn-darkorange btn-xs'>下移</a></td></tr>");
                    } else {
                        let html = "";
                        let childItemArr = JSON.parse(info.content);
                        for (let i = 0; i < childItemArr.length; i++) {
                            html += childItemArr[i].optValue + "." + childItemArr[i].childTitle + "</br>";
                        }
                        $("#questionlist").append("<tr data-value='" + info.recordId + "'><td>" + index + "</td><td>" + examType + "</td><td>" + info.title + "</td>" +
                            "<td>" + html + "</td><td><a onclick=\"deleteChildItem(this)\" class='btn btn-darkorange btn-xs'>删除</a>&nbsp;&nbsp;<a onclick=\"toup(this)\" class='btn btn-darkorange btn-xs'>上移</a>&nbsp;&nbsp;<a onclick=\"todown(this)\" class='btn btn-darkorange btn-xs'>下移</a></td></tr>");

                    }
                }
            }
        }
    })
}

function toup(Obj) {
    var before = $(Obj).parent().parent().prev();
    $(Obj).parent().parent().after(before);
}

function todown(Obj) {
    var next = $(Obj).parent().parent().next();
    $(Obj).parent().parent().before(next);
}
